package cn.jsxz.controller.api;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.setting.dialect.Props;
import cn.jsxz.common.constants.Constants;
import cn.jsxz.common.utils.ResultUtil;
import cn.jsxz.common.utils.WeiXinUtil.WxPayUtil;
import cn.jsxz.entity.OrderInfo;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @ClassName WxPayApi
 * @Description TODO
 * @Author Admin
 * @Date 13:45
 * @Version 1.0
 **/
@RestController
@RequestMapping("/api/wxPay")
public class WxPayApi {


    /**
     * 微信支付下单接口
     *
     * @Title: xiadan @Description: TODO @param @param shopId @param @param
     * request @param @return @param @throws Exception 参数 @return
     * JSONObject 返回类型 @throws
     */
    @RequestMapping(value = "wxPlacingOrder", method = RequestMethod.POST)
    public JSONObject wxPlacingOrder(@RequestParam(value = "orderId") String orderId, @RequestParam(value = "payMoney") String payMoney, HttpServletRequest request) throws Exception {
        Props props = new Props("workConfig.properties", "utf-8");
        String openId = request.getParameter("openId");
        Double money = Double.parseDouble(payMoney);
        if (null == payMoney) {
            return ResultUtil.resultJSON(300, "去支付失败,金额不能为空", null);
        }
        if (money <= 0) {
            return ResultUtil.resultJSON(300, "去支付失败,总金额不能小于0元", null);
        }
        //拼接订单对象参数
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOpenid(openId);//用户在商户appid下的唯一标识
        orderInfo.setOut_trade_no(orderId);//订单号
        orderInfo.setAppid(props.getStr("APPID"));// 微信分配的小程序ID
        orderInfo.setBody(orderInfo.getOut_trade_no());
        orderInfo.setMch_id(props.getStr("SJID"));//微信支付分配的商户号
        orderInfo.setTrade_type("JSAPI");//程序取值如下：JSAPI，详细说明见参数规定
        orderInfo.setNotify_url(props.getStr("serverUrl"));//异步接收微信支付结果通知的回调地址
        orderInfo.setTotal_fee(Integer.parseInt(payMoney) * 100);//订单总金额，单位为分，详见支付金额
        orderInfo.setSign_type("MD5");
        orderInfo.setSpbill_create_ip(request.getRemoteAddr());
        orderInfo.setNonce_str(RandomUtil.simpleUUID());
        String payResult = WxPayUtil.xiadan(orderInfo);
        System.out.println("微信返回:" + payResult);
        Map<String, String> stringStringMap = WxPayUtil.readStringXmlOut(payResult);
        String prepayId = stringStringMap.get("prepay_id");
        if (null != prepayId) {
            JSONObject result = WxPayUtil.signPrepay(prepayId);
            return ResultUtil.resultJSON(200, "预下单请求成功", result);
        } else {
            return ResultUtil.resultJSON(Constants.HTTP_STATE_CODE.ERROR_300, "预下单请求失败", null);
        }
    }

    /**
     * @auther: Zy
     * @method wxPayCallback
     * 功能描述: 微信支付回调接口
     * @params: [request, response]
     * @return: * @return : java.lang.String
     * @date: 2019-02-15 13:58:18
     */
    @RequestMapping(value = "wxPayCallback")
    public String wxPayCallback(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String inputLine;
        String notityXml = "";
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        // 微信给返回的东西
        try {
            while (((inputLine = request.getReader().readLine()) != null)) {
                notityXml += inputLine;
            }
            request.getReader().close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map payResult = WxPayUtil.doXMLParse11(notityXml);
        if ("SUCCESS".equals(payResult.get("return_code")) && "SUCCESS".equals(payResult.get("result_code"))) {
            String orderId = (String) payResult.get("out_trade_no");//单号
            String totalPrice = (String) payResult.get("total_fee");//金额
            //业务处理



            System.out.println("支付成功!");
            return WxPayUtil.setXml("SUCCESS", "OK");
        } else {
            System.out.println("支付失败");
            return "fail";
        }
    }
}
